package rand

import (
	"crypto/rand"
	"math"
	"math/big"

	"gitee.com/makitdone/gx"
	"github.com/gookit/goutil/comdef"
)

func Rand[T gx.Number](n T) (T, error) {
	randInt, err := rand.Int(rand.Reader, big.NewInt(int64(math.Floor(float64(n)))))
	if err != nil {
		return 0, err
	}
	return T(randInt.Int64()), nil
}

// 获取随机小数，介于 0 和 1
func Random(bit int) (float64, error) {
	max := math.Pow10(bit)
	if value, err := Rand(max); err == nil {
		return value / max, nil
	} else {
		return 0, err
	}
}

// 获取随机小数，介于 0 和 1
func MustRandom(bit int) float64 {
	if value, err := Random(bit); err != nil {
		panic(err)
	} else {
		return value
	}
}

// 获取随机整数，介于 min 和 max
func RandInt[T comdef.Int](min T, max T) (T, error) {
	randInt, err := rand.Int(rand.Reader, big.NewInt(int64(max-min+1)))
	if err != nil {
		return 0, err
	}
	return T(randInt.Int64()) + min, nil
}

// 获取随机整数，介于 min 和 max
func MustRandInt[T comdef.Int](min T, max T) T {
	if value, err := RandInt(min, max); err != nil {
		panic(err)
	} else {
		return value
	}
}
